<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.10.3"></script>
<body>
<script>

function loadImage(url) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = "anonymous";
    img.src = url;
    img.onload = () => resolve(img);
    img.onerror = reject;
  });
}

async function loadBinaryDataFromUrl(url) {
  const req = new Request(url);
  const res = await fetch(req);
  if (!res.ok) {
    throw Error(res.statusText);
  }
  return res.arrayBuffer();
}

async function render(rootElem, data) {
  const canvas = document.createElement('canvas');
  rootElem.append(canvas);

  await tf.toPixels(data, canvas);

  return canvas;
}

// load and render image data
(async function(){
  
  const url = "../data/cat.jpeg";
  const img = await loadImage(url);
  const data = tf.fromPixels(img);

  data.print();
  render(document.body, data);

  const dataResized = tf.image.resizeBilinear(data, [100, 100]);
  render(document.body, dataResized);
}());

// load and render binary data
(async function(){
  
  const size = 100;
  const buf = await loadBinaryDataFromUrl('../data/rand.bin');
  const data = tf.tensor2d(new Float32Array(buf), [size, size]);

  data.print();
  await render(document.body, data);

  const data3d = data.expandDims(2);
  const dataResized = tf.image.resizeBilinear(data3d, [227, 227]);
  await render(document.body, dataResized);
}());

</script>
</body>